import 'dart:async';

import 'package:bike_ride/common/mvvm/base_page.dart';
import 'package:bike_ride/common/net/dio_client.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/util/language.dart';
import 'package:bike_ride/common/util/sp_utils.dart';
import 'package:bike_ride/common/widget/dialog/mydialog.dart';
import 'package:bike_ride/main/app.dart';
import 'package:bike_ride/model/login/view/login_mobile_v.dart';
import 'package:bike_ride/model/login/view_model/login_vm.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:bike_ride/router/routers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'login_protocol_v.dart';

enum LoginType {
  empty,
  phone, //手机登录
  email, //邮箱登录
}

///登录
class LoginView extends BaseStatefulPage<LoginViewModel> {
  const LoginView({super.key});

  @override
  LoginViewState createState() => LoginViewState();
}

class LoginViewState extends BaseStatefulPageState<LoginView, LoginViewModel> {
  final ValueNotifier<bool> _isAgreePrivacy = ValueNotifier<bool>(false);

  @override
  void initAttribute() {}

  @override
  void initObserver() {}

  @override
  void initContextObserver(BuildContext context) {
    super.initContextObserver(context);
    Language().initLocal(context);
  }

  @override
  LoginViewModel viewBindingViewModel() {
    return LoginViewModel()..viewState = this;
  }

  void naviNextPage() {
    NavigatorUtil.push(context, Routers.appMainPage,clearStack:true);
  }

  @override
  Widget appBuild(BuildContext context) {
    return SafeArea(
      child: WillPopScope(child: Scaffold(
        extendBodyBehindAppBar: true,
        backgroundColor: ColorStyles.color_FFFFFF,
        appBar: AppBar(
          leading: BackButton(onPressed: () {
            if (viewModel!.loginType.value != LoginType.empty) {
              viewModel!.loginType.value = LoginType.empty;
            } else {
              NavigatorUtil.push(navigatorKey.currentContext!,
                  Routers.appMainPage,clearStack: true
              );
            }
          }),
          title: Container(),
          backgroundColor: Colors.transparent,
        ),
        body: GestureDetector(
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: ListView.builder(
            itemBuilder: (context, index) {
              return getListViewWidget()[index];
            },
            padding: EdgeInsets.symmetric(horizontal: 28.rpx, vertical: 60.rpx),
            itemCount: getListViewWidget().length,
          ),
        ),
        bottomNavigationBar: GestureDetector(
          onTap: (){
            Language().showPicker(context);
          },
          child: SizedBox(
            height: 40.rpx,
            child: Center(
              child: Text(
                S.current.switchLanguage,
                style: TextStyle(
                    fontSize: 24.rpx, color: ColorStyles.color_999999),
              ),
            ),
          ),
        ),
      ), onWillPop: ()async{
        launchConfirmationDialog();
        return false;
      }),
    );
  }

  List<Widget> getListViewWidget() {
    return [
      Stack(
        children: [
          Align(
            alignment: Alignment.topCenter,
            child: Image.asset('assets/common_v2/login_bg_v3.png',
                fit: BoxFit.fitHeight, height: MediaQuery.of(context).size.height * 0.5),
          ),
          ValueListenableBuilder<String>(
            valueListenable: viewModel!.appName,
            builder: (context, value, _) {
              return Positioned(
                top: 60.rpx,
                left: 0,
                child: GestureDetector(
                  onLongPress: (){
                    final openProxy = SpUtils.getBool(SpUtilsKey.$proxySwitch,defValue: false);
                    SpUtils.putBool(SpUtilsKey.$proxySwitch,!openProxy);
                    DioClient().proxy(reset: true);
                  },
                  child: RichText(
                      text: TextSpan(children: [
                        TextSpan(
                          text: '${S.current.hello} $value',
                          style: TextStyle(
                              fontSize: 48.rpx, color: ColorStyles.color_333333),
                        ),
                        TextSpan(
                            text: '\nHello！ Welcome！',
                            style: TextStyle(
                                color: ColorStyles.color_666666, fontSize: 24.rpx)),
                      ])),
                ),
              );
            },
          ),
        ],
      ),
      ValueListenableBuilder(
          valueListenable: viewModel!.loginType,
          builder: (context, data, _) {
            if (data == LoginType.empty) {
              return Column(
                children: [
                  ValueListenableBuilder(
                      valueListenable: _isAgreePrivacy,
                      builder: (context, data, _) {
                        return ProtocolCheck(
                          current: data,
                          onChanged: (value) {
                            _isAgreePrivacy.value = value;
                          },
                        );
                      }),
                  SizedBox(
                    height: 24.rpx,
                  ),
                  // GestureDetector(
                  //   onTap: () {
                  //     // 快捷登录
                  //   },
                  //   child: Container(
                  //     height: 88.rpx,
                  //     padding: const EdgeInsets.symmetric(vertical: 8),
                  //     decoration: BoxDecoration(
                  //       borderRadius: BorderRadius.all(Radius.circular(20.rpx)),
                  //       color: Theme.of(context).colorScheme.primary,
                  //     ),
                  //     child: Center(
                  //       child: Text(
                  //         S.current.loginQuick,
                  //         style:
                  //             TextStyle(fontSize: 32.rpx, color: Colors.white),
                  //       ),
                  //     ),
                  //   ),
                  // ),
                  SizedBox(height: 28.rpx,),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        viewModel!.loginType.value = LoginType.phone;
                      });
                    },
                    child: Container(
                      height: 88.rpx,
                      padding: const EdgeInsets.symmetric(vertical: 8),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(20.rpx)),
                        color: Theme.of(context).colorScheme.primary,
                      ),
                      child: Center(
                        child: Text(
                          S.current.loginPhoneAndEmail,
                          style: TextStyle(
                              fontSize: 32.rpx,
                              color: ColorStyles.color_FFFFFF),
                        ),
                      ),
                    ),
                  ),
                ],
              );
            } else if (data == LoginType.phone) {
              return PhoneTypeWidget(
                viewModel: viewModel!,
                onSuccess: naviNextPage,
                isAgreePrivacy: _isAgreePrivacy.value,
              );
            }
            throw UnimplementedError();
          }),
    ];
  }

  void launchConfirmationDialog() {
    // 显示确认对话框
    showAlertDialog(
      context: context,
      confirmName: S.current.confirm,
      cancelName: S.current.cancel,
      title: S.current.dialogTitle,
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Image.asset('assets/common_v2/icon_bus_routes_new.png',
            width: 96.rpx,
            height: 96.rpx,),
          SizedBox(height: 16.rpx,),
          Text(S.current.sureLeaveAPP,style: TextStyle(fontSize: 28.rpx,color: ColorStyles.color_333333),)
        ],
      ),
      onConfirm: () async{
        await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
      },
    );
  }
}




